import {
	ref,
	onMounted,
	watch,
	useAttrs,
	computed,
	defineProps
} from 'vue';
import {getIcons} from "@/api/easybook/icons.js";
import {pageConfig} from "@/utils/globalVar.js";
export function selectProps() {
	return {
		modelValue: {
			type: [String,
				Number],
			default: () => ''
		}
	}
}
export function selectEmits() {
	return ['update:modelValue']
}
export function selectMixin(props,
                            {
	                            emit,
	                            idKey,
	                            nameKey,
	                            dataKey,
	                            api
                            }) {
	const attrs = useAttrs();
	const ready = ref(false);
	const selectData = ref(undefined);
	const loading = ref(false);
	const options = ref([]);
	const showValue = computed({
		get() {
			if (props.modelValue) {
				getIcons(props.modelValue)
					.then((res) => {
						selectData.value = res.data
					})
			}
			return props.modelValue
		},
		set(value) {
			emit('update:modelValue',
				value)
		}
	})
	const remoteMethod = (query) => {
		loading.value = true
		api({
			[nameKey]: query,
			...pageConfig
		})
			.then(res => {
				options.value = res[dataKey]
				loading.value = false
			})
	}
	onMounted(() => {
		ready.value = false
		if (!!props.modelValue) {
			api({
				[idKey]: props.modelValue,
				...pageConfig
			})
				.then((res) => {
					options.value = res[dataKey]
					ready.value = true
				})
		} else {
			api({
				...pageConfig
			})
				.then((res) => {
					options.value = res[dataKey]
					ready.value = true
				})
		}
	})
	return {
		ready,
		loading,
		options,
		selectData,
		showValue,
		remoteMethod,
		attrs
	};
}
